import {
	ref,
	watch
} from 'vue';

export const usePagination = function (api: Function, {
	// 自动运行
	auto = false,
	// 默认参数
	defaultParam = {},
	// 监听变化重新请求
	watchRefresh = [],
	// 请求回来的数据转换
	transform = (res) => res,
	// 分页字段的key名字
	pageKeyName = "page",
	// 请求之前
	beforeCallBack = () => {},
	// 成功回调
	successCallBack = (res) => {},
	// 无论如何都会指定
	completeCallBack = (res) => {}
} = {}) {
	const message = '由至慧果能提供技术支持'
	const loading = ref(false)
	const isMoreLoading = ref(false)
	const error = ref(false)
	const list = ref([])
	const page = ref(1)
	const isMore = ref(true)
	const runApi = async (param = {}) => {
		try {
			beforeCallBack()
			let res = await api({
				[pageKeyName]: page.value,
				pageSize: 10,
				simplePage: 1,
				...defaultParam,
				...param
			})
			res = await transform(res)
			if (res.length === 0 || res.length < 10) isMore.value = false
			list.value = [...list.value, ...res]
			successCallBack(res)
		} catch (e) {
			error.value = true
			throw e
		} finally {
			completeCallBack(list.value)
		}
	}
	// 自动运行
	if (auto) {
		loading.value = true;
		runApi().finally(() => {
		  loading.value = false;
		})
	}

	// 监听变化重新请求
	watch(watchRefresh, () => {
		console.log('变化了', api)
		refresh()
	}, { deep: true });

	//刷新
	async function refresh(param?: object) {
		try {
			clear()
			loading.value = true
			await runApi(param)
			return list.value
		} finally {
			loading.value = false
		}
	}
	//加载更多
	async function loadmore(param) {
		if (!isMore.value) {
			// uni.showToast({
			// 	icon: "none",
			// 	title: '没有更多了'
			// })
			return list.value
		}
		try {
			isMoreLoading.value = true
			++page.value
			await runApi(param)
		} catch (e) {
			--page.value
		} finally {
			isMoreLoading.value = false
		}
	}
	//清空数据恢复状态
	function clear() {
		loading.value = false
		isMoreLoading.value = false
		error.value = false
		isMore.value = true
		page.value = 1
		list.value = []
	}
	return {
		loading,
		isMoreLoading,
		error,
		list,
		loadmore,
		refresh,
		isMore,
		page,
		clear,
		message
	}
}
